package com.lisen.common.base.ui;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.lisen.common.Constant;
import com.lisen.common.base.util.RequestUtil;

public class BaseServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2321934906911480952L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Map<String, String[]> params = req.getParameterMap();
		Set<String> keys = params.keySet();
		for (String key : keys) {
			String[] o = params.get(key);
			int size = o.length;
			for (int i = 0; i < size; i++) {
				o[i] = new String(o[i].getBytes("ISO-8859-1"), "utf-8");
			}
		}
		resp.setCharacterEncoding("utf-8");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
	}

	// 获得当前用户名
	public String getCurrentUserName(HttpServletRequest req) {
		return (String) req.getSession().getAttribute("UserLogin");
	}

	// 获得当前用户ID
	public String getCurrentUserId(HttpServletRequest req) {
		return (String) req.getSession().getAttribute("UserID");
	}

	// 中文文件编码
	public String encodeFileName(HttpServletRequest request, String fileName)
			throws UnsupportedEncodingException {
		String agent = request.getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("MSIE")) {
			if (agent.indexOf("7.0") != -1) {// IE7
				String name = new String(fileName.getBytes("GBK"), "ISO-8859-1");
				return name;
			} else {// IE6
				return URLEncoder.encode(fileName, "UTF8");
			}
		} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// FIRE
			// FOX
			return "=?UTF-8?B?"
					+ (new String(Base64.encodeBase64(fileName
							.getBytes("UTF-8")))) + "?=";
		} else {
			return fileName;
		}
	}

	// 获得请求参数
	public StringBuffer getParameterStr(HttpServletRequest req) {
		StringBuffer exportParam = new StringBuffer();
		Enumeration<?> names = req.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement().toString();
			try {
				exportParam.append(name).append("=").append(
						java.net.URLEncoder.encode(req.getParameter(name),
								"utf-8")).append("&");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return exportParam;
	}

	// 发送错误消息
	public void sendFailMessage(String message, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		if (message != null) {
			req.setAttribute("message", message);
		} else {
			req.setAttribute("message", "操作失败!");
		}
		req.getRequestDispatcher("/page/common/fail.jsp").forward(req, resp);
		return;
	}

	// 发送消息
	public void sendSuccessMessage(String message, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		if (message != null) {
			req.setAttribute("message", message);
		} else {
			req.setAttribute("message", "操作成功！");
		}
		req.getRequestDispatcher("/page/common/fail.jsp").forward(req, resp);
	}

	// 系统初始化
	public void init() throws ServletException {
		super.init();
		ServletContext context = super.getServletContext();
		Constant.SYS_WEB_DIR = context.getRealPath("/");// web目录
		// 日志
		String logDirPath = (Constant.SYS_WEB_DIR
				.endsWith(Constant.SYS_FILE_SEPARATOR) ? Constant.SYS_WEB_DIR
				.substring(0, Constant.SYS_WEB_DIR.length() - 1)
				: Constant.SYS_WEB_DIR)
				+ Constant.SYS_FILE_SEPARATOR + "log";
		File logDir = new File(logDirPath);
		StringBuffer logPath = new StringBuffer(logDirPath).append(
				Constant.SYS_FILE_SEPARATOR).append("log.txt");
		if (!logDir.exists()) {
			logDir.mkdirs();
			File logFile = new File(logPath.toString());
			if (!logFile.exists()) {
				try {
					logFile.createNewFile();
					System.out.println("make log file");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			System.out.println("make log dir");
		}
		Constant.LOG_FILE = logPath.toString();
		System.out.println("logDirPath:" + logDirPath);
		System.out.println("Constant.LOG_FILE: " + Constant.LOG_FILE);
	}

	// 获得基本路径
	public String getBasePath(HttpServletRequest req) {
		return RequestUtil.getBasePath(req);
	}

}
